package org.mcflier.appuntamento.io.driver.rss.imdb;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.LinkedList;

import org.gnu.stealthp.rsslib.RSSChannel;
import org.gnu.stealthp.rsslib.RSSException;
import org.gnu.stealthp.rsslib.RSSHandler;
import org.gnu.stealthp.rsslib.RSSItem;
import org.gnu.stealthp.rsslib.RSSParser;
import org.mcflier.appuntamento.data.model.IMDBList;
import org.mcflier.appuntamento.io.driver.rss.RssTools;
import org.mcflier.appuntamento.io.exception.RSSConnectionException;
import org.mcflier.appuntamento.io.exception.RSSParsingException;

public class RssLib4JDriver extends AbstractRssImdbDriver {
	
	@Override
	public IMDBList getList(String link) throws RSSConnectionException, RSSParsingException {
		this.logger.info("Getting RSS list: "+link);
		RSSHandler handler = new RSSHandler();
		try {
			RSSParser.parseXmlFile(RssTools.getRSSContentFile(link).getAbsolutePath(), handler, false);
			RSSChannel channel = handler.getRSSChannel();
			IMDBList list = new IMDBList(channel.getTitle(), link);
			list.setDescription(channel.getDescription());
			list.setLastBuildDate(RssTools.convertToTimestamp(channel.getLastBuildDate()));
			list.setPubDate(RssTools.convertToTimestamp(channel.getPubDate()));
			LinkedList itemsList = channel.getItems();
			for (Object object : itemsList) {
				RSSItem item = (RSSItem)object;
				IMDBList.IMDBListItem imdbItem = list.new IMDBListItem(
						item.getTitle(),
						item.getLink(),
						item.getLink(),
						item.getDescription(),
						RssTools.convertToTimestamp(item.getPubDate()),
						null);
				list.addItem(imdbItem);
			}
			
			return list;
		} catch (MalformedURLException e) {
			throw new RSSConnectionException("Malformed rss url: "+link, e);
		} catch (RSSException e) {
			throw new RSSParsingException("Error parsing the rss file: "+link, e);
		} catch (IOException e) {
			throw new RSSConnectionException("Error accessing url content: "+link, e);
		}
	}

	@Override
	public IMDBList getListById(String idList) throws RSSConnectionException, RSSParsingException {
		String prefix = this.getProperties().getProperty(RSS_URL_LIST_PREFIX);
		if(!prefix.endsWith("/")) prefix+="/";
		
		return this.getList(prefix+idList);
	}
}
